﻿#include "udp_master.h"
#include "msg_clientdata.h"
#include "net_data.h"

UDPMaster::UDPMaster()
{
	//    mType = 0;//Unicast
	//    mType = 1;//Broadcast
	mType = 2;//Multicast
    //InitSocket("235.0.0.20",10020);

}

void UDPMaster::InitSocket(QString serverIP, int port)
{
	//初始化socket，设置组播地址
	mUdpSocket = new QUdpSocket;
	mGroupAdress.setAddress(serverIP);
	if (mType == 0 || mType == 1)
	{
		//绑定本地IP和端口号
        mUdpSocket->bind(port);
	}
	else if (mType == 2)
	{
		if (mUdpSocket->bind(QHostAddress::AnyIPv4, port, QUdpSocket::ShareAddress))
		{
			//加入组播地址
			mUdpSocket->joinMulticastGroup(mGroupAdress);
			qDebug() << ("Join Multicast Adrress [") << mGroupAdress.toString()
				<< ("] Successful!") << endl;
		}
	}
	else
	{
		qDebug() << "mType is error! " << endl;
		return;
	}

	connect(mUdpSocket, &QUdpSocket::readyRead, this, [=] {
		ReadPendingDataframs();
		});
}



void UDPMaster::ReadPendingDataframs()
{
	QByteArray _data;
	_data.resize(mUdpSocket->pendingDatagramSize());
	if (mType == 0)//Unicast
	{
		QHostAddress* _peerHostAddress = new QHostAddress("192.168.1.199");
		quint16 _port = 10010;
		while (mUdpSocket->hasPendingDatagrams())
		{
			mUdpSocket->readDatagram(_data.data(), _data.size(), _peerHostAddress, &_port);//接收指定IP和端口的udp报文
			qDebug() << "Unicast ==> Receive data : " << QString::fromLatin1(_data) << endl;
		}
	}
	else if (mType == 1)//Broadcast
	{
		QHostAddress _peerHostAddress;
		quint16 _port;
		while (mUdpSocket->hasPendingDatagrams())
		{
			mUdpSocket->readDatagram(_data.data(), _data.size(), &_peerHostAddress, &_port);//接收同一子网的udp报文
			qDebug() << "Broadcast ==> Receive data : " << QString::fromLatin1(_data) << endl;
		}
	}
	else if (mType == 2)//Multicast
	{
		QHostAddress _peerHostAddress;
		quint16 _port;
		while (mUdpSocket->hasPendingDatagrams())
		{
			mUdpSocket->readDatagram(_data.data(), _data.size(), &_peerHostAddress, &_port);//接收同组的udp报文
			//qDebug() << "Multicast ==> Receive data : " << QString::fromLatin1(_data) << endl;

			///////////////////////////
			Msg_ClientData clientData;
			clientData.Parse(_data, _data.size());
			///////////////////////////

			QVector<LowerNode*>& lower_data = NetData::Instance()->lower_data;

			QVector<LowerNode*>::iterator it = lower_data.begin();
			QVector<LowerNode*>::iterator it_end = lower_data.end();

			int i = 0;
			while (it != it_end)
			{
				(*it)->Value.append(clientData.value[i]);

				i++;
				it++;
			}

			emit sigNewData();
		}
	}
	else
	{
		qDebug() << "mType is error! " << endl;
		return;
	}
}
